﻿// controller to handle the viewing of images
angular.module('app.user').controller('UserViewImagesController', [
    '$scope', 'libraryService', 'dataService',
	function ($scope, libraryService, dataService) {

		var instance = this;
		var loadFolderId = -1;
		// function to load the images
		this.loadImagesData = function () {
			// if no model user then do not load the data
    		if ($scope.model.user === null || $scope.model.user === undefined) {
    			return;
    		}
			// if no folder id, do not load
    		if (loadFolderId.toString() === $scope.getFolderId().toString()) {
    			return;
    		}
    		// get the folder Id to load the images for
    		loadFolderId = $scope.getFolderId();
			// set the fetch images request with the no results message
    		$scope.fetchImages(function () { return libraryService.getImagesInFolder($scope.model.user.Id, loadFolderId); }, 'No images were found in the folder');
		};
		// function to load the favorite images
		this.loadFavoritesData = function () {
			// do not call the server if there is no authenticated user
			if ($scope.model.authUser === null || $scope.model.authUser === undefined) {
				return;
			}
			// set the fetch images request to download the favorite images from the server and the matching no images response message
			$scope.fetchImages(function () {
				return dataService.download('FavoriteImage', 'FavoriteImage.UserId = ' + $scope.model.authUser.Id.toString());
			}, 'You have no favorite images.');
		};
		// function to load the data
		this.loadData = function () {
			// if viewing favorites, then load the favorites
			if ($scope.isViewingFavorites()) {
				instance.loadFavoritesData();
			}
			else {
				// load the images for the folder
				instance.loadImagesData();
			}
		};
		// if the model user changes, load the images
		$scope.$watch('model.user', function () {
    		instance.loadData();
    	});
		// if the folder changes, load the images
    	$scope.$watch('model.params.folderId', function () {
    		instance.loadData();
    	});
    }]);